package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CommentService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 分页查询动态评论
     *
     * @param page
     * @param pagesize
     * @param movementId
     * @return
     */
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //1.调用api查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //2.判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3.提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //4.调用userApi查询用户信息
        Map<Long, UserInfo> ids = userInfoApi.findByIds(userIds, null);
        //5.封装vo
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            //一个comment封装一个vo
            UserInfo userInfo = ids.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0L, vos);
    }

    /**
     * 发布评论
     *
     * @param movementId
     * @param comment
     */
    public void saveComments(String movementId, String comment) {
        //1.获取用户id
        Long userId = UserHolder.getUserId();
        //2.构造comment
        Comment comment1 = new Comment();
        comment1.setUserId(userId);
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setContent(comment);
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setCreated(System.currentTimeMillis());
        //3.调用api保存评论
        Integer count = commentApi.saveComments(comment1);
        log.info("count=" + count);
    }

    @Autowired
    private MqMessageService mqMessageService;
    /**
     * 点赞
     *
     * @param movementId
     * @return
     */
    public Integer like(String movementId) {
        Long userId = UserHolder.getUserId();
        //1.调用api查看是否已经点赞
        boolean flag = commentApi.like(movementId, userId, CommentType.LIKE);
        //2.已经点赞 抛出异常
        if (flag) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.调用api保存数据到Mongodb
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.saveComments(comment);
        //4、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //动态点赞日志
        mqMessageService.sendLogService(userId, "0203", "movement", movementId);
        return count;
    }

    /**
     * 取消点赞
     *
     * @param movementId
     * @return
     */
    public Integer dislike(String movementId) {
        Long userId = UserHolder.getUserId();
        //1.调用api查看是否已经点赞
        boolean flag = commentApi.like(movementId, userId, CommentType.LIKE);
        //2.如果没有点赞，抛出异常
        if (!flag) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.调用api删除数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LIKE.getType());
        Integer count = commentApi.delete(comment);
        //4、拼接redis的key，将redis中的key删除
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        Object hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key, hashKey);
        //动态取消点赞日志
        mqMessageService.sendLogService(userId, "0206", "movement", movementId);
        return count;
    }

    /**
     * 喜欢
     *
     * @param movementId
     * @return
     */
    public Integer love(String movementId) {
        Long userId = UserHolder.getUserId();
        //1.调用api查看是否已经喜欢
        boolean flag = commentApi.isLove(movementId, userId, CommentType.LOVE);
        //2.已经喜欢，抛出异常
        if (flag) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.调用api保存数据到mongo
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(movementId));
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.saveComments(comment);
        //4.拼接redis的key,把已经喜欢的标识存到redis中
        String key = Constants.MOVEMENT_LOVE_HASHKEY + movementId;
        Object hashKey = Constants.MOVEMENT_LOVE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //动态喜欢日志
        mqMessageService.sendLogService(userId, "0204", "movement", movementId);
        return count;
    }

    /**
     * 取消喜欢
     *
     * @param movementId
     * @return
     */
    public Integer dislove(String movementId) {
        Long userId = UserHolder.getUserId();
        //1.调用api查看是否已经喜欢
        boolean flag = commentApi.isLove(movementId, userId, CommentType.LOVE);
        //2.没有喜欢，抛出异常
        if (!flag) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.调用api删除数据库中的数据
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setPublishId(new ObjectId(movementId));
        Integer count = commentApi.delete(comment);
        //4.删除redis中已经喜欢的标识key
        String key = Constants.MOVEMENT_LOVE_HASHKEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key, hashKey);
        //动态取消喜欢日志
        mqMessageService.sendLogService(userId, "0207", "movement", movementId);
        return count;
    }

    /**
     * 评论点赞
     *
     * @param id
     * @return
     */
    public Integer isLike(String id) {
        Comment byId = commentApi.findById(id);
        Long userId = UserHolder.getUserId();
        //1.调用api查看是否已经点赞
        boolean flag = commentApi.like(id, userId, CommentType.LIKE);
        //2.已经点赞就抛出异常
        if (flag) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.调用api保存数据到数据库
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(id));
        comment.setPublishUserId(byId.getUserId());
        Integer count = commentApi.saveLike(comment);
        //4.拼接redis的key,把已经点赞的标识存到redis中
        String key = Constants.MOVEMENT_LIKE_HASHKEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    /**
     * 取消评论点赞
     *
     * @param id
     * @return
     */
    public Integer isNoLike(String id) {
        Comment byId = commentApi.findById(id);
        Long userId = UserHolder.getUserId();
        //1.调用api判断评论是否点赞
        boolean flag = commentApi.like(id, userId, CommentType.LIKE);
        //2.没有点赞就抛出异常
        if (!flag) {
            throw new BusinessException(ErrorResult.error());
        }
        //3.删除数据中对应的数据,返回点赞数
        Comment comment = new Comment();
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(userId);
        comment.setPublishId(new ObjectId(id));
        comment.setPublishUserId(byId.getUserId());
        Integer count = commentApi.deleteLike(comment);
        //4.删除redis中已经点赞的标识
        String key = Constants.MOVEMENT_LIKE_HASHKEY + id;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }



    public Integer common(String movementId, boolean ao, CommentType commentType) {
        Long userId = UserHolder.getUserId();
        //1.调用api判断评论是否点赞
        boolean flag = commentApi.common(movementId, userId, commentType);
        //2.没有点赞就抛出异常
        if (!flag && ao == false) {
            throw new BusinessException(ErrorResult.error());
        } else if (flag && ao == true) {
            throw new BusinessException(ErrorResult.error());
        }

        Integer count = 0;
        Comment comment = new Comment();
        //3.调用api保存数据到Mongodb
        if (ao = true) {
            comment.setUserId(userId);
            comment.setPublishId(new ObjectId(movementId));
            comment.setCommentType(commentType.getType());
            comment.setCreated(System.currentTimeMillis());
            count = commentApi.saveComments(comment);
            //4、拼接redis的key，将用户的点赞状态存入redis
            String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
            String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
            redisTemplate.opsForHash().put(key, hashKey, "1");
            return count;
        } else {
            //3.调用api删除数据
            comment.setPublishId(new ObjectId(movementId));
            comment.setUserId(userId);
            comment.setCommentType(commentType.getType());
            count = commentApi.delete(comment);
            //4、拼接redis的key，将redis中的key删除
            String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
            Object hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
            redisTemplate.opsForHash().delete(key, hashKey);
            return count;
        }
    }
}
